<template>
  <div class="p-6px">
    <el-card class="rounded-md" shadow="never">
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true" @submit.prevent>
        <el-form-item label="卡券名称" prop="username">
          <el-input placeholder="请输入卡券名称" v-model="searchParams.name" clearable style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-debounce="handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-throttle="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:role:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refresh-table="handleListPage"></KoiToolbar>
      </el-row>

      <br />
      <el-table
        v-loading="loading"
        v-adaptive
        border
        :data="tableList"
        empty-text="暂时没有数据哟"
      >
        <el-table-column label="序号" prop="id" width="80px" fixed="left" align="center" type="index"></el-table-column>
        <el-table-column
          label="卡券名称"
          prop="name"
          align="center"
          fixed="left"
          width="200px"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="卡券类型" prop="type" width="100px" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ scope.row.type == 1 ? "满减券" : "满折券" }}
          </template>
        </el-table-column>
        <el-table-column label="优惠金额" prop="" align="center" width="200px" :show-overflow-tooltip="true">
          <template #default="scope">
            <div>
              {{
                scope.row.type == 1
                  ? `满${scope.row.threshold_amount}减${scope.row.amount}元`
                  : `满${scope.row.threshold_amount}打${scope.row.discount / 10}折`
              }}
            </div>
            {{ scope.row.type == 1 ? "" : `最大扣减金额${scope.row.max_discount_amount}元` }}
          </template>
        </el-table-column>
        <el-table-column label="发放数量" prop="icon" width="150px" align="center">
          <template #default="scope">
            {{ scope.row.is_limit_num == 2 ? "无限制" : `发放数量:${scope.row.total_num}` }}
          </template>
        </el-table-column>
        <el-table-column label="累计领取数量" prop="received_num" width="150px" align="center"></el-table-column>
        <el-table-column label="使用数量" prop="used_num" width="150px" align="center"></el-table-column>
        <el-table-column label="每人最大领取数量" width="150px" prop="max_receive_num" align="center"></el-table-column>
        <el-table-column label="状态" prop="status_text" align="center"> </el-table-column>
        <el-table-column label="有效期类型" width="150px" prop="validity_type_text" align="center"> </el-table-column>
        <el-table-column label="有效期" prop="" width="230px" align="center">
          <template #default="scope">
            {{
              scope.row.validity_type == 1
                ? `${(scope.row.start_time || "").slice(0, 10)} 到 ${(scope.row.end_time || "").slice(0, 10)}`
                : `领取之后:${scope.row.receive_useful_day}天`
            }}
          </template>
        </el-table-column>
        <el-table-column label="商品参与方式" width="150px" prop="join_goods_text" align="center"> </el-table-column>
        <el-table-column label="创建时间" prop="create_time" width="200" align="center"> </el-table-column>
        <el-table-column
          label="操作"
          align="left"
          width="350"
          fixed="right"
          v-auth="['system:role:update', 'system:role:delete']"
        >
          <template #default="{ row }">
            <el-button type="primary" size="small" plain @click="handleUpdate(row)" v-auth="['system:role:update']">
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <br />
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="searchParams.pageNo"
        v-model:page-size="searchParams.pageSize"
        v-show="total > 0"
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />

      <!-- 添加 OR 修改 -->
      <KoiDrawer
        ref="koiDrawerRef"
        :title="title"
        @koi-confirm="handleConfirm"
        @koi-cancel="handleCancel"
        :loading="confirmLoading"
        :size="800"
      >
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="180px" status-icon>
            <el-form-item label="优惠券名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入优惠券名称" clearable />
            </el-form-item>
            <el-form-item label="优惠券类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio label="满减券" :value="1"></el-radio>
                <el-radio label="折扣券" :value="2"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="优惠券面额" prop="amount" v-if="form.type == 1">
              <el-input v-model="form.amount" placeholder="请输入优惠券面额" clearable />
            </el-form-item>
            <el-form-item label="折扣比例" prop="discount" v-if="form.type == 2">
              <el-input type="number" max="100" v-model="form.discount" placeholder="请输入优惠券折扣比例">
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="最大抵扣金额" prop="max_discount_amount" v-if="form.type == 2">
              <el-input type="number" v-model="form.max_discount_amount" placeholder="请输入最大抵扣金额" />
            </el-form-item>

            <el-form-item label="限制发放数量" prop="is_limit_num">
              <el-radio-group v-model="form.is_limit_num">
                <el-radio label="限制" :value="1"></el-radio>
                <el-radio label="不限" :value="2"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="发放数量" prop="total_num" v-if="form.is_limit_num == 1">
              <el-input type="number" v-model="form.total_num" placeholder="请输入发放数量" clearable />
            </el-form-item>

            <el-form-item label="每人最多领取数量" prop="max_receive_num">
              <el-input type="number" v-model="form.max_receive_num" placeholder="请输入每人最多领取数量" clearable />
            </el-form-item>
            <el-form-item label="是否有门槛" prop="is_threshold">
              <el-radio-group v-model="form.is_threshold">
                <el-radio label="有门槛" :value="1"></el-radio>
                <el-radio label="无门槛" :value="2"></el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="门槛金额" prop="threshold_amount" v-if="form.is_threshold == 1">
              <el-input type="number" v-model="form.threshold_amount" placeholder="请输入门槛金额" clearable />
            </el-form-item>
            <el-form-item label="有效期类型" prop="validity_type">
              <el-radio-group v-model="form.validity_type">
                <el-radio label="固定日期" :value="1"></el-radio>
                <el-radio label="领取之后N天" :value="2"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="有效期" prop="time" v-if="form.validity_type == 1">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                value-format="YYYY-MM-DD"
                start-placeholder="开始日期"
                range-separator="至"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              />
            </el-form-item>
            <el-form-item label="领取后" prop="receive_useful_day" v-if="form.validity_type == 2">
              <el-input type="number" max="100" v-model="form.receive_useful_day">
                <template #append>天</template>
              </el-input>
            </el-form-item>

            <el-form-item label="指定用户分组可领取" prop="user_group_ids">
              <el-select v-model="form.user_group_ids" placeholder="请选择用户分组" multiple>
                <el-option v-for="(item, index) in selectOptions.user_group" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="指定用户等级可领取" prop="user_level_ids">
              <el-select v-model="form.user_level_ids" placeholder="请选择用户等级" multiple>
                <el-option v-for="(item, index) in selectOptions.user_level" :key="index" :label="item.title" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="指定用户标签可领取" prop="user_tag_ids">
              <el-select v-model="form.user_label_ids" placeholder="请选择用户标签" multiple>
                <el-option v-for="(item, index) in selectOptions.user_label" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>

            <el-form-item label="商品参与方式" prop="join_goods">
              <el-radio-group v-model="form.join_goods">
                <el-radio label="全部商品" :value="1"></el-radio>
                <el-radio label="指定商品" :value="2"></el-radio>
              </el-radio-group>
            </el-form-item>


            
            <el-form-item label="指定商品分类可用" prop="goods_category_ids" v-if="form.join_goods==1">
              <el-cascader
                placeholder="请选择商品分类"
                v-model="form.goods_category_ids"
                :options="selectOptions.goods_category"
                :show-all-levels="false"
                :props="{
                  multiple: true
                }"
              >
              </el-cascader>
            </el-form-item>
            <el-form-item label="指定商品品牌可用" prop="goods_brand_ids" v-if="form.join_goods==1">
              <el-select v-model="form.goods_brand_ids" placeholder="请选择商品品牌" multiple>
                <el-option v-for="(item, index) in selectOptions.goods_brand" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="指定商品标签可用" prop="goods_tag_ids" v-if="form.join_goods==1">
              <el-select v-model="form.goods_tag_ids" placeholder="请选择商品标签" multiple>
                <el-option v-for="(item, index) in selectOptions.goods_tag" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
       


            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="待启用" :value="1"></el-radio>
                <el-radio label="进行中" :value="2"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </template>
      </KoiDrawer>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="memberLevelPage">
import { onMounted, reactive, ref } from "vue";
import { koiMsgError, koiMsgWarning, koiNoticeError } from "@/utils/koi.ts";
import { add, read, listPage, update } from "@/plugin/coupon/api/coupon/index.ts";
import { handleTree, koiDatePicker } from "@/utils/index.ts";
import { getBrand } from "@/api/pms/brand";
import { cascaderList } from "@/api/pms/cate";
import { getAllUserGroup } from "@/api/user/group";
import { getAllUserLabel } from "@/api/user/label";
import { getAllUserLevel } from "@/api/user/level";
import { getAllTags } from "@/api/pms/tags";

// 数据表格加载页面动画
const loading = ref(false);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 数据表格数据
const tableList = ref<any>([]);
// 查询参数
const searchParams = ref({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  name: ""
});

const total = ref<number>(0);

// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    name: ""
  };
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.pageNo = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleListPage();
};

// 时间
const dateRange = ref();
/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选中条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listPage(koiDatePicker(searchParams.value, dateRange.value, "created"));
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

onMounted(() => {
  // 获取数据表格数据
  handleListPage();
});

/** 添加 */
const handleAdd = async () => {
  // 重置表单
  resetForm();
  await initSelect();
  // 标题
  title.value = "添加";
  koiDrawerRef.value.koiOpen();
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  if (id == null || id == "") {
    koiMsgWarning("请选择需要修改的数据");
    return;
  }
  try {
    const res: any = await read(id);
    form.value = res.data;
    dateRange.value = [form.value.start_time, form.value.end_time];
  } catch (error) {
    koiNoticeError("数据获取失败，请刷新重试");
    console.log(error);
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 重置表单
  resetForm();
  await initSelect();
  // 标题
  title.value = "修改";
  if (row.id == null || row.id == "") {
    koiMsgError("请选中需要修改的数据");
  }
  handleEcho(row.id);
  koiDrawerRef.value.koiOpen();
};

const selectOptions = ref<any>({
  goods_category: [],
  goods_brand: [],
  goods_tag: [],
  user_group: [],
  user_level: [],
  user_label: []
});

const initSelect = async () => {
  Promise.all([cascaderList(), getBrand(), getAllTags(), getAllUserGroup(), getAllUserLevel(), getAllUserLabel()]).then(
    (res: any) => {
      const goods_category = res[0].data;
      selectOptions.value.goods_brand = res[1].data;
      selectOptions.value.goods_tag = res[2].data;
      selectOptions.value.user_group = res[3].data;
      selectOptions.value.user_level = res[4].data;
      selectOptions.value.user_label = res[5].data;

      if (goods_category != null && goods_category != undefined && goods_category.length > 0) {
        selectOptions.value.goods_category = handleTree(goods_category, "value", "pid");
      }

      console.log(`selectOptions.value.goods_category`, JSON.stringify(selectOptions.value.goods_category));
    }
  );
};

/** 添加 AND 修改抽屉 */
const koiDrawerRef = ref();
// 标题
const title = ref("");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  name: "",
  value: []
});

/** 清空表单数据 */
const resetForm = () => {
  form.value = {
    name: "",
    value: []
  };
};

/** 表单规则 */
const rules = reactive({
  type: [{ required: true, message: "请选择优惠券类型", trigger: "blur" }],
  discount: [{ required: true, message: "请输入折扣比例", trigger: "blur" }],
  max_discount_amount: [{ required: true, message: "请输入最大优惠金额", trigger: "blur" }],
  amount: [{ required: true, message: "请输入优惠券面额", trigger: "blur" }],
  is_limit_num: [{ required: true, message: "请设置是否限制发放数量", trigger: "blur" }],
  is_threshold: [{ required: true, message: "请设置是否有门槛", trigger: "blur" }],
  total_num: [{ required: true, message: "请输入发放总数量", trigger: "blur" }],
  max_receive_num: [{ required: true, message: "请输入每人最大领取数量", trigger: "blur" }],
  threshold_amount: [{ required: true, message: "请输入门槛金额", trigger: "blur" }],
  validity_type: [{ required: true, message: "请选择有效期类型", trigger: "blur" }],
  join_goods: [{ required: true, message: "请选择商品参与类型", trigger: "blur" }],
  receive_useful_day: [{ required: true, message: "请选择有效期天数", trigger: "blur" }]
});

// 确定按钮是否显示loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      try {
        if (form.value.validity_type == 1) {
          form.value.start_time = dateRange.value[0] || "";
          form.value.end_time = dateRange.value[1] || "";
        }
        form.value.goods_category_ids = Array.from(new Set(form.value.goods_category_ids.flat()));
        if (form.value.id != null && form.value.id != "") {
          await update(form.value);
        } else {
          await add(form.value);
        }
        resetForm();
        handleListPage();
        koiDrawerRef.value.koiQuickClose();
      } catch (error) {
        console.log(error);
        confirmLoading.value = false;
        koiNoticeError("操作失败，请刷新重试");
      } finally {
        confirmLoading.value = false;
      }
    } else {
      koiMsgError("验证失败，请检查填写内容");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDrawerRef.value.koiClose();
};
</script>

<style lang="scss" scoped></style>
